package cn.aifeix.basic.service.impl;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.basic.constant.BaseConstant;
import cn.aifeix.basic.dto.AccountLoginDto;
import cn.aifeix.basic.dto.LoginPhoneSmsCodeDto;
import cn.aifeix.basic.dto.PhoneLoginDto;
import cn.aifeix.basic.dto.WxLoginDto;
import cn.aifeix.basic.jwt.JwtUtils;
import cn.aifeix.basic.jwt.RsaUtils;
import cn.aifeix.basic.jwt.UserInfo;
import cn.aifeix.basic.service.ILoginService;
import cn.aifeix.basic.util.AjaxResult;
import cn.aifeix.basic.util.HttpUtil;
import cn.aifeix.basic.util.MD5Utils;
import cn.aifeix.basic.util.StrUtils;
import cn.aifeix.system.domain.Menu;
import cn.aifeix.system.mapper.MenuMapper;
import cn.aifeix.system.mapper.PermissionMapper;
import cn.aifeix.user.domain.Logininfo;
import cn.aifeix.user.domain.User;
import cn.aifeix.user.domain.Wxuser;
import cn.aifeix.user.mapper.LogininfoMapper;
import cn.aifeix.user.mapper.UserMapper;
import cn.aifeix.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Service
@Slf4j
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")
    private String privateRsaKey;
    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> accountLogin(AccountLoginDto dto) {
        // 判断非空
        // 判断账号是否存在 loginifo
        Logininfo logininfo = logininfoMapper.findByUsername(dto.getUsername(),dto.getType());
        if (null == logininfo){
            throw new BussinessException("账号或密码错误");
        }
        // 判断密码是否正确
        String encrypPassword = MD5Utils.encrypByMd5(logininfo.getSalt() + dto.getPassword());
        if (StringUtils.isBlank(encrypPassword) || !encrypPassword.equals(logininfo.getPassword())){
            throw new BussinessException("账号或密码错误");
        }
        return getMap(logininfo);
    }

    private Map<String, Object> getMap(Logininfo logininfo) {
        // 使用jwt方案
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(privateRsaKey)
                .getFile());
        Map<String, Object> hashMap = new HashMap<String, Object>();
        UserInfo user = new UserInfo();
        user.setLogininfo(logininfo);
        if (0 == logininfo.getType()){
            // 如果是后端 那么我们需要将权限放到token中
            // 菜单权限
            List<String> permissions = permissionMapper.findByLogininfoId(logininfo.getId());
            // 按钮权限
            List<Menu> menus = menuMapper.findByLogininfoId(logininfo.getId());
            user.setPermissions(permissions);
            user.setMenus(menus);
            hashMap.put("permissions", permissions);
            hashMap.put("menus", menus);
        }
        String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 300);
        // 将logininfo敏感字段置空
        logininfo.setPassword("");
        logininfo.setSalt("");
        logininfo.setPhone("");
        // 返回给前端
        hashMap.put("token", token);
        hashMap.put("logininfo", logininfo);
        return hashMap;
    }
//    private Map<String, Object> getMap(Logininfo logininfo) {
//        // 将token 和logininfo添加到redis中
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
//        // 将logininfo敏感字段置空
//        logininfo.setPassword("");
//        logininfo.setSalt("");
//        logininfo.setPhone("");
//        // 返回给前端
//        Map<String,Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo", logininfo);
//        return map;
//    }
    /**
     * 获取手机验证码
     * @param dto
     */
    @Override
    public void loginSmsCode(LoginPhoneSmsCodeDto dto) {
        // 参数非空校验PhoneSmsCodeDto里已做
        // 手机号格式验证
        if (!Pattern.matches("^1[3|4|5|7|8][0-9]{9}$",dto.getPhone())){
            throw new BussinessException("手机号码格式错误！");
        }
        // 校验图形验证码是否正确
        // 获取redis中的uuid
        String imageCode = (String) redisTemplate.opsForValue().get(dto.getImageCodeKey());
        if (StringUtils.isBlank(imageCode) || !imageCode.equalsIgnoreCase(dto.getImageCodeValue())){
            throw new BussinessException("图形验证码错误！");
        }
        // 判断该手机号是否在数据库
        Logininfo logininfo = logininfoMapper.findByPhone(dto.getPhone(),dto.getType());
        // 没找到就直接注册
        if(null == logininfo){
            // 将手机号添加到数据库
            logininfo = new Logininfo();
            logininfo.setUsername(dto.getPhone());
            logininfo.setPhone(dto.getPhone());
            // 设置一个默认的密码及盐值
            String salt = StrUtils.getComplexRandomString(32);
            String encrypByMd5 = MD5Utils.encrypByMd5(salt + "1");
            logininfo.setSalt(salt);
            logininfo.setPassword(encrypByMd5);
            logininfo.setType(dto.getType());
            // 添加到数据库
            logininfoMapper.add(logininfo);
            // 同步到user表中
            User user = new User();
            user.setLogininfoId(logininfo.getId());
            BeanUtils.copyProperties(logininfo,user);
            user.setState(1);
            userMapper.add(user);
        }
        // 两次发送短信间隔是否大于60s
        String redisSmsCode = (String)redisTemplate.opsForValue().get("loginByPhoneCode"+dto.getPhone());
        String smsCode = "";
        if (StringUtils.isNotBlank(redisSmsCode)){
            String[] split = redisSmsCode.split(":");
            smsCode = split[0];
            // 当前时间
            long newTime = System.currentTimeMillis();
            // reids中的时间
            long oldTime = Long.valueOf(split[1]);
            if (newTime - oldTime < 60 * 1000){
                throw new BussinessException("滚！");
            } else {
                log.info(smsCode);
                // 重新发送老的验证码并重置有效期
                redisTemplate.expire("loginByPhoneCode"+dto.getPhone(),5,TimeUnit.MINUTES);
            }
        }else {
            // 生成验证码
            smsCode = StrUtils.getRandomString(4);
        }
        log.info("验证码为：{}",smsCode);
        String redisValue = smsCode+":"+ System.currentTimeMillis();
        // 保存到redis中 key=getPhoneCode:手机号 value=验证码：时间戳，设置5分钟有效时间
        redisTemplate.opsForValue().set("loginByPhoneCode"+dto.getPhone(),redisValue,5,TimeUnit.MINUTES);
        // 发送短信
//        SendSmsUtil.send(dto.getPhone(),"你好：你的验证码为："+smsCode+"，5分钟内有效！");
    }

    /**
     * 手机验证码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> phoneLogin(PhoneLoginDto dto) {
        verifySmsCode("loginByPhoneCode"+dto.getPhone(), dto.getSmsCode());
        // 通过手机号去查询Logininfo
        Logininfo logininfo = logininfoMapper.findByPhone(dto.getPhone(),dto.getType());
        // 没有就直接注册
        if (null == logininfo) {
            // 添加这个手机号到数据库中
            logininfo = new Logininfo();
            logininfo.setUsername(dto.getPhone());
            logininfo.setPhone(dto.getPhone());
            // 盐值密码设置默认值
            String salt = StrUtils.getComplexRandomString(32);
            String pwd = MD5Utils.encrypByMd5(salt + "1");
            logininfo.setSalt(salt);
            logininfo.setPassword(pwd);
            logininfo.setType(dto.getType());
            // 添加到数据库中
            logininfoMapper.add(logininfo);
            // 并且需要同步到user表中
            User user = new User();
            user.setLogininfoId(logininfo.getId());
            BeanUtils.copyProperties(logininfo,user);
            userMapper.add(user);
        }
        // 生成一个token
        String token = UUID.randomUUID().toString();
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechatLogin(WxLoginDto dto) {
        // 参数非空校验
        if(StringUtils.isBlank(dto.getCode())){
            throw new BussinessException("参数不能为空");
        }
        // 通过抽取方法获取openid
        Pair<String, String> pair = this.getOpenidAndToken(dto.getCode());
        String openid = pair.getRight();
        // 根据openid去wx_user查
        Wxuser wxuser = wxuserMapper.findByopenid(openid);
        if (null != wxuser && null != wxuser.getUserId()){
            // 证明之前已登录过且已绑定 可直接登录
            // 返给前端token logininfo
            Logininfo logininfo = logininfoMapper.findByUserId(wxuser.getUserId());
            Map<String, Object> map = getMap(logininfo);
            return AjaxResult.me().success(map);
        }
        // 没绑定则返给前端accessToken、openid
        StringBuffer sb = new StringBuffer()
                .append("?accessToken=")
                .append(pair.getLeft())
                .append("&openId=").append(pair.getRight());
        return AjaxResult.me().fail("nobinder").setResultObj(sb);
    }

    /**
     * 微信登录绑定
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> wechatBinder(WxLoginDto dto) {
        // 校验参数非空
        // 校验验证码是否正确
        this.verifySmsCode(String.format(BaseConstant.VerfityCodeCons.BINDER_SMSCODE_PHONE,dto.getPhone()),dto.getVerifyCode());
        // 调用微信接口 获取用户信息
        String url = String.format(BaseConstant.WxLoginCons.WX_LOGIN_USER_INFO, dto.getAccessToken(), dto.getOpenId());
        String s = HttpUtil.httpGet(url);
        // json字符串转成实体
        Wxuser wxuser = JSONObject.parseObject(s, Wxuser.class);
        // 查user表中是否存在 没有存三张表 有存一张
        User user = userMapper.findByPhone(dto.getPhone());
        Logininfo logininfo = new Logininfo();
        if (null == user){
            // 初始化user对象
            user = initUser(dto);
            // 初始化logininfo对象
            logininfo = initLogininfo(user);
            // 保存 logininfo
            logininfoMapper.add(logininfo);
            // 保存user
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }else {
            // 通过LogininfoId获取logininfo对象
            logininfo = logininfoMapper.findById(user.getLogininfoId());
        }
        // 保存wxuser
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);
        return getMap(logininfo);
    }

    /**
     * 初始化logininfo
     * @param user
     * @return
     */
    private Logininfo initLogininfo(User user){
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 初始化User
     * @param dto
     * @return
     */
    private User initUser(WxLoginDto dto){
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 密码
        String password = salt + "1";
        String encryPwd = MD5Utils.encrypByMd5(password);
        return User
                .builder()
                .username(dto.getPhone())
                .phone(dto.getPhone())
                .salt(salt)
                .password(encryPwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    /**
     * 短信验证码校验
     */
    private void verifySmsCode(String redisKey,String smsCode) {
        String redisSmsCode = (String) redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isBlank(redisSmsCode)) {
            throw new BussinessException("验证码错误！");
        }
        if (!smsCode.equals(redisSmsCode.split(":")[0])) {
            throw new BussinessException("验证码错误！");
        }
    }

    /**
     * 抽取的获取openid和token的方法
     * @param code
     * @return
     */
    private Pair<String,String> getOpenidAndToken(String code){
        // 用code去调用微信接口获取token和openid
        String tokenUrl = String.format(BaseConstant.WxLoginCons.WX_LOGIN_TOKEN_URL, BaseConstant.WxLoginCons.WX_LOGIN_APPID,
                BaseConstant.WxLoginCons.WX_LOGIN_SECRET, code);
        String s = HttpUtil.httpGet(tokenUrl);
        // 将json字符串转成json对象
        JSONObject jsonObject = JSONObject.parseObject(s);
        // 拿到token
        String accessToken = jsonObject.getString("access_token");
        // 拿到openid
        String openid = jsonObject.getString("openid");
        return Pair.of(accessToken,openid);
    }

}
